<template>
    <BasicDrawer
      v-bind="$attrs"
      @register="registerDrawer"
      showFooter
      title="授权模版"
      width="800px"
      @ok="handleSubmit"
    >
      <BasicForm @register="registerForm">
      </BasicForm>

      <Card :title="item.label" v-for="item in selectedEntities" :key="item.label" :bordered="false" class="!mt-5">
        <EntityConfigForm ref="entityFormRefs" :fieldOptions="item.fieldOptions" />
      </Card>

    </BasicDrawer>
  </template>
  <script lang="ts" setup>
    import { ref } from 'vue';
    import { BasicForm, useForm, FormSchema } from '@/components/Form';
    import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
    import EntityConfigForm from './CertificateEntity.vue';
    import { Card } from 'ant-design-vue';
  
    import { getEntityList } from '@/api/entity'
    import { createCertificateTemplate, editCertificateTemplate } from '@/api/certificateTemplate'
  
    const emit = defineEmits(['success', 'register']);
    const isUpdate = ref(true);
    const id = ref();
    const selectedEntities = ref([]);
    const entityFormRefs = ref([]);
    const entityOptionsRef = ref<EntityOption[]>([]);
    const entityMap = new Map();

    const schemas: FormSchema[] = [
      {
        field: 'name',
        label: '模板名称',
        component: 'Input',
      },
      {
        field: 'desc',
        label: '模板描述',
        component: 'Input',
      },
      {
        field: 'data',
        label: '可访问数据',
        component: 'ApiSelect',
        componentProps: {
          mode: 'multiple',
          options: entityOptionsRef,
          allowClear: true,
          onChange: (event, value) => {
            if (value === undefined) {
              const selectValues: any = [];
              for (const e of event) {
                if (entityMap.has(e.key)) {
                  selectValues.push(entityMap.get(e.key));
                }
              }
              selectedEntities.value = selectValues;
            } else {
              selectedEntities.value = value;
            }
          },
        },
      },
    ];
  
    const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
      labelWidth: 90,
      baseColProps: { span: 24 },
      schemas: schemas,
      showActionButtonGroup: false,
    });

    interface EntityOption {
      value: string,
      label: string,
      fieldOptions: any[],
    }

    async function initEntityOptions() {
      const result = await getEntityList();
      const items = result.items;
      const options: EntityOption[] = [];
      for (const item of items) {
        const option: EntityOption = {
          value: item.key,
          label: item.name,
          fieldOptions: item.fields,
        };
        options.push(option);
        entityMap.set(item.key, option);
      }
      entityOptionsRef.value = options;
    }
  
    const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
      selectedEntities.value = [];
      entityFormRefs.value = [];
      await initEntityOptions();
      isUpdate.value = data?.isUpdate;
      id.value = data?.record?.id;
      resetFields();
      setDrawerProps({ confirmLoading: false });
      
      if (!!isUpdate.value) {
        setFieldsValue({
          ...data.record,
        });

        const entityFormValues: any = [];
        for (const item of data.record.data) {
          entityFormValues.push({
            fields: item.fields,
            ext_filter: item.ext_filter,
          });
        }
        setTimeout(()=>{
          for (const [idx, formRef] of entityFormRefs.value.entries()) {
            formRef.setFieldsValue({...entityFormValues[idx]})
          }
        }, 100);
      }
    });
  
    async function handleSubmit() {
      const validates = [];
      for (const formRef of entityFormRefs.value) {
        validates.push(formRef.validate());
      }
      const formValues = await Promise.all(validates);
      const entities = [];
      for (const [idx, entity ] of selectedEntities.value?.entries()) {
        const formValue = formValues[idx];
        const item = {
          key: entity.value,
          fields: formValue.fields,
          ext_filter: formValue.ext_filter,
        };
        entities.push(item);
      }
      try {
        const values = await validate();
        values.data = entities;
        setDrawerProps({ confirmLoading: true });
        if (!!isUpdate.value) {
          await editCertificateTemplate(id.value, values);
        } else {
          await createCertificateTemplate(values);
        }
        closeDrawer();
        emit('success');
      } finally {
        setDrawerProps({ confirmLoading: false });
      }
    }
  </script>